//定义局部锁

#include <iostream>
#include <unistd.h>
#include <vector>
#include "thread.hpp"

string GetThreadName()
{
    static int number = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", number++);
    return name;
}

int ticket = 10000; // 全局的共享资源

void GetTicket(pthread_mutex_t* mutex)
{
    while (true)
    {   
        pthread_mutex_lock(mutex); 
        if (ticket > 0)
        {
            // 充当抢票花费的时间
            usleep(1000);
            printf("get a ticket : %d\n", ticket);
            ticket--;
            pthread_mutex_unlock(mutex);
        }
        else
        {
            pthread_mutex_unlock(mutex);
            break;
        }
        // 实际情况, 还有后续的动作
    }
}

int main()
{
    pthread_mutex_t mutex; //定义局部锁
    pthread_mutex_init(&mutex, nullptr); //初始化局部锁

    string name1 = GetThreadName();
    Thread<pthread_mutex_t*> t1(name1, GetTicket, &mutex);

    string name2 = GetThreadName();
    Thread<pthread_mutex_t*> t2(name2, GetTicket, &mutex);

    string name3 = GetThreadName();
    Thread<pthread_mutex_t*> t3(name3, GetTicket, &mutex);

    string name4 = GetThreadName();
    Thread<pthread_mutex_t*> t4(name4, GetTicket, &mutex);

    t1.start();
    t2.start();
    t3.start();
    t4.start();

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    pthread_mutex_destroy(&mutex); //初始化局部锁
    return 0;
}

